﻿using System.Net.WebSockets;
using System.Security.Claims;

namespace DongFangGuoKai.WCSPlatform.WebApi.Utils.WebSocketCommon
{
    /// <summary>
    /// WebSocket中间件
    /// </summary>
    public class WebSocketMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly WebSocketHandler _webSocketHandler;
        private readonly WebSocketConnectManager connectionManager;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="next"></param>
        /// <param name="webSocketHandler"></param>
        /// <param name="connectionManager"></param>
        public WebSocketMiddleware
        (
            RequestDelegate next,
            WebSocketHandler webSocketHandler,
            WebSocketConnectManager connectionManager
        )
        {
            _next = next;
            _webSocketHandler = webSocketHandler;
            this.connectionManager = connectionManager;
        }

        // Invoke 方法用于处理 HTTP 请求
        public async Task Invoke(HttpContext context)
        {
            //判断是否为WebSocket请求
            if (context.WebSockets.IsWebSocketRequest)
            {
                var socket = await context.WebSockets.AcceptWebSocketAsync();
                var clientIpAddress = context.Connection.RemoteIpAddress?.ToString();
                connectionManager.AddSocket(clientIpAddress, socket);                // 管理起来这次连接
                await _webSocketHandler.Handle(socket, context, clientIpAddress);
            }
            else
            {
                // 如果不是 WebSocket 请求，则继续执行下一个中间件
                await _next(context);
            }
        }

    }
}
